﻿using DingTalk.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using Top.Api;

namespace DingWeb.Controllers.DingDing
{
    /// <summary>
    /// 回调事件
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CallBackController : Controller
    {
        private readonly ILogger<CallBackController> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public CallBackController(ILogger<CallBackController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        ///回调事件
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        [HttpPost]
        public Dictionary<string, string> Index(string signature, string timestamp, string nonce, PostBody body)
        {

            //body = new PostBody()
            //{
            //    encrypt = "G0bdYA4VTE3AFwrzYSeWdnRLBvFPjRoIfF9Wu4ZqaosW4kUAEdfT25DmbSMDd+0Cmz95joUNdYk7WGzwlkPU5eIxeslwV+EVFIwBJsQPNIiPGImOg1E2Lz9micw8kMu5"
            //};

            Dictionary<string, string> successMap = new Dictionary<string, string>();
            try
            {
                //接收encrypt参数
                string encryptStr = body.encrypt;

                ////实例化钉钉解密类构造参数为对应的 应用中的token、appkeys、AppKey值
                DingTalkEncryptor dingTalkEncryptor = new DingTalkEncryptor("WqxCYyS8oLCuy7f7wM6bZc8twjfYlbZ3m2lbc81dDO", "8pSdPBgtO1d8kazlwRq4EeGxJ3mGEARynfGLuJOJSQq", AppConfigurtaionHelper.Configuration["DingDing:AppKey"]);
                //定义字符串接收解密后的值
                string returnDate = dingTalkEncryptor.getDecryptMsg(signature, timestamp, nonce, encryptStr);
                JToken jToken = JToken.Parse(returnDate);
                //取出事件类型字段
                string EventType = jToken["EventType"].ToString();
                //_logger.LogInformation("returnDate:" + returnDate);
                //_logger.LogInformation("encryptStr:" + encryptStr);
                //_logger.LogInformation("EventType:" + EventType);
                switch (EventType)
                {
                    //用户新增事件
                    case "user_add_org": break;
                    //加班单
                    case "bpms_task_change":
                        //流程完成+同意
                        //考勤 打卡 
                        if (!string.IsNullOrEmpty(returnDate))
                        {
                            TaskChange(returnDate);
                        }
                        break;
                    case "attendance_check_record":
                        //考勤 打卡
                        string DataList = jToken["DataList"].ToString();
                        if (!string.IsNullOrEmpty(DataList))
                        {
                            Atendance(DataList);
                        }
                        break;
                    default: break;
                }
                successMap = dingTalkEncryptor.getEncryptedMap("success");

                return successMap;
            }
            catch (DingTalkEncryptException ex)
            {
                _logger.LogDebug("Callback:" + ex.ToString());
            }
            return successMap;
        }

        /// <summary>
        /// 加班单
        /// </summary>
        /// <param name="str"></param>
        private void TaskChange(string str)
        {
            try
            {
                //List<EventDataList> list = JsonConvert.DeserializeObject<List<EventDataList>>(str);
                //if (list != null && list.Count > 0)
                //{   //只处理第一条
                //    //增加到考勤记录

                //    //获取资格

                //}
            }
            catch (Exception ex)
            {
                _logger.LogError("str---------------------" + ex.ToString());
            }
        }
        /// <summary>
        /// 考勤
        /// </summary>
        /// <param name="str"></param>
        private void Atendance(string str)
        {
            try
            {
                List<EventDataList> list = JsonConvert.DeserializeObject<List<EventDataList>>(str);
                if (list != null && list.Count > 0)
                {   //只处理第一条
                    //增加到考勤记录

                    //获取资格

                }
            }
            catch (Exception ex)
            {
                _logger.LogError("str---------------------" + ex.ToString());
            }
        }
    }

    public class PostBody
    {
        public string encrypt { get; set; }
    }

    public class EventProcessInstance
    {
        public string processInstanceId { get; set; }
        public long finishTime { get; set; }
        public string corpId { get; set; }
        public string EventType { get; set; }
        public string businessId { get; set; }
        public string title { get; set; }
        public string type { get; set; }
        public string result { get; set; }

        public long createTime { get; set; }

        public string processCode { get; set; }

        public string bizCategoryId { get; set; }

        public string businessType { get; set; }

        public string staffId { get; set; }

        public long taskId { get; set; }
    }

    public class EventDataList
    {
        public string address { get; set; }
        public string baseMacAddr { get; set; }
        public long checkTime { get; set; }
        public string corpId { get; set; }
        public string locationResult { get; set; }
        public string groupId { get; set; }
        public string bizId { get; set; }
        public string locationMethod { get; set; }
        public bool checkByUser { get; set; }
        public string deviceName { get; set; }
        public string deviceSN { get; set; }
        public string userId { get; set; }
    }
}
